<template>
    <div class="app-container review">
        <div class="search">
            <el-input class="inputWidth" v-model="search.authorName" placeholder="作者" clearable></el-input>
            <el-date-picker 
                v-model="timeRange" 
                type="daterange" 
                align="right" 
                unlink-panels 
                range-separator="-" 
                start-placeholder="创建时间起" 
                end-placeholder="创建时间止" 
                value-format="yyyy-MM-dd HH:mm:ss" 
                :picker-options="pickerOptions"
                clearable
            >
            </el-date-picker>
            <el-select v-model="search.auditStatus" placeholder="状态" clearable>
                <el-option
                v-for="item in status"
                :key="item.code"
                :label="item.msg"
                :value="item.code">
                </el-option>
            </el-select>
            <el-button type="primary" @click="searchAdvisory">查询</el-button>
        </div>
        <div class="list">
            <el-table 
                :data="list" 
                v-loading="tableLoading" element-loading-text="数据加载中，请稍后" 
                border fit highlight-current-row 
            >
                <el-table-column align="center" label="资讯标题" show-overflow-tooltip>
                    <template slot-scope="scope">
                        {{scope.row.title}}
                    </template>
                </el-table-column>
                <el-table-column align="center" label="状态">
                    <template slot-scope="scope">
                        {{scope.row.auditStatusDesc}}
                    </template>
                </el-table-column>
                <el-table-column align="center" label="作者" show-overflow-tooltip>
                    <template slot-scope="scope">
                        {{scope.row.authorName}}
                    </template>
                </el-table-column>
                <el-table-column align="center" label="创建时间">
                    <template slot-scope="scope">
                        {{scope.row.createTime | dateformat('YYYY-MM-DD HH:mm')}}
                    </template>
                </el-table-column>
                <el-table-column align="center" label="更新时间">
                    <template slot-scope="scope">
                        {{scope.row.updateTime | dateformat('YYYY-MM-DD HH:mm')}}
                    </template>
                </el-table-column>
                <el-table-column align="center" label="操作">
                    <template slot-scope="scope">
                        <el-button size="small" @click="reviewDetail(scope.$index, scope.row.id, scope.row.authorId)">审核</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div v-show="!tableLoading" class="pagination">
                <el-pagination 
                    @size-change="handleSizeChange" 
                    @current-change="handleCurrentChange" 
                    :current-page.sync="search.pageNo" 
                    :page-sizes="[10,20,30,50]" 
                    :page-size="search.pageSize" 
                    layout="total, sizes, prev, pager, next, jumper" 
                    :total="total"
                >
                </el-pagination>
            </div>
        </div>
        <el-dialog width="70%" :visible.sync="dialogFormVisible" class="popBox" :before-close="handleClose">
            <el-form 
                ref="dataForm" 
                :model="review" 
                label-width="100px"
                :rules="rules" 
            >
                <el-row>
                    <div class="sub-navbar">
                        <el-button style="margin-left: 10px;" size="small" @click="checkAdvisory(0)">审核不通过
                        </el-button>
                        <el-button style="margin-left: 10px;" type="success" size="small" @click="checkAdvisory(1)">审核通过
                        </el-button>
                    </div>
                </el-row>
                <div class="boxCont">
                    <el-row>
                        <el-col :span="24">
                            <div class="postInfo-container">
                            <el-row>
                                <el-col :span="6">
                                <el-form-item label-width="90px" label="栏目资讯：">
                                    <el-cascader
                                        change-on-select  placeholder="请选择" expand-trigger="click"
                                        :options="sections"
                                        v-model="review.sectionIds"
                                        class="width"
                                    ></el-cascader>
                                </el-form-item>
                                </el-col>
                                <el-col :span="14">
                                    <el-tooltip  class="item" effect="dark" content="请输入标题" placement="top">
                                        <el-form-item label-width="110px" label="标题：" prop="title">
                                        <el-input style="min-width:380px" placeholder="请输入标题" maxlength="100" v-model="review.title">
                                        </el-input>
                                        </el-form-item>
                                    </el-tooltip>
                                </el-col>
                                <el-col :span="4">
                                    <div style="margin-top:10px;font-size:14px;margin-left:10px">
                                        <span>您还可以输入{{ 100 - review.title.length }}个字</span>
                                    </div>
                                </el-col>
                            </el-row>
                            </div>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label-width="110px" label="设置标签：">
                            <multiselect style="line-height:initial" 
                                v-model="labelIds" 
                                :options="labels" 
                                @search-change="getLabelOptions" 
                                placeholder="搜索标签" 
                                selectLabel="选择" 
                                :multiple="true" 
                                deselectLabel="删除" 
                                track-by="id" 
                                :internalSearch="false" 
                                label="name"
                            >
                                <span slot='noResult'>无搜索结果</span>
                            </multiselect>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label-width="110px" label="投放区域：" class="postInfo-container-item" prop="nickname">
                          <multiselect style="line-height:initial" v-model="review.areaVal" :options="areaOptions" selectLabel="选择" :multiple="true" deselectLabel="删除" track-by="value" label="label">
                          </multiselect>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item>
                          <span>注：如果选择了"全国"，则不能选择其他省份</span>
                        </el-form-item>
                      </el-col>                      
                    </el-row>
                    <el-row>
                      <el-form-item label="是否为广告：">
                        <el-radio-group v-model="review.isAd">
                          <el-radio :label="1">是</el-radio>
                          <el-radio :label="0">否</el-radio>
                        </el-radio-group>
                      </el-form-item>
                  </el-row>
                    <el-row>
                        <el-col :span="12">
                          <el-form-item label-width="110px" label="上传封面：" class="postInfo-container-item">
                            <el-upload
                              class="upload-demo"
                              :headers="headers"
                              action="/tools/oss/upload"
                              :on-remove="handleRemove"
                              :on-success="handleUploadSuccess"
                              list-type="picture"
                              :file-list="file"
                              :limit="2" >
                            <el-button size="small" type="primary">上传封面</el-button>
                          </el-upload>
                        </el-form-item>  
                      </el-col>                      
                    </el-row>                    
                    <el-row>
                        <el-col :span="20">
                            <div class="editor-container">
                            <el-tooltip  class="item" effect="dark" content="请输入内容" placement="top">
                                <el-form-item label-width="110px" label="资讯内容：" prop="content">
                                <Tinymce :height=400 ref="editor" v-model="review.content"  :value="review.content"/>
                                </el-form-item>
                            </el-tooltip>
                            </div>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="6">
                            <el-form-item label-width="110px" label="设置权重：">
                                <el-input-number v-model="review.weight" :step="1" :min="0"></el-input-number>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="6">
                            <el-form-item label-width="110px" label="设置浏览量：">
                                <el-input-number  v-model="review.view" :step="1" :min="0"></el-input-number>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="6">
                            <el-form-item label-width="110px" label="设置点赞数：">
                                <el-input-number  v-model="review.likeCount" :step="1" :min="0"></el-input-number>
                            </el-form-item>
                        </el-col> 
                    </el-row>
                </div>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
import { auditStatus, advisoryList, reviewDetail, getSectionCascade, getInfoLabels, checkAdvisory } from '@/api/advisory'
import Multiselect from 'vue-multiselect' // 使用的一个多选框组件，element-ui的select不能满足所有需求
import 'vue-multiselect/dist/vue-multiselect.min.css' // 多选框组件css
import Tinymce from '@/components/Tinymce'
import { getToken } from '@/utils/auth' // 验权
import { getAreaList } from '@/api/activity'

export default {
  components: { Tinymce, Multiselect },
  data(){
    return{
      areaOptions: [],
      search:{
        pageNo: 1,
        pageSize: 10
      },
      timeRange:null,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      status:[],
      list:[],
      tableLoading: true,
      total: null,
      dialogFormVisible: false,
      labelIds:[],
      review: {
        id: null,
        authorId: null,
        sectionIds:[],
        title: '',
        content: '',
        cover: '',
        labels: [],
        labelId: [],
        labelNames: [],
        likeCount : 10,
        view: 10,
        weight: 100,
        areaVal: [],
        provinceIds: [],
        isAd: 0
      },
      sections: [],
      labels: [],
      headers:{},
      file:[],
      rules:{
        title: [{ required: true, message: '标题必填', trigger: 'blur' }]
      }
    }
  },
  watch:{
    // 监控是否选择了“全国” 如果选择了，那么不能选择其他省份
    'review.areaVal'(e){
      if(e){
        if(e.label || e.toString() == []){
          return
        }else if(e[e.length - 1].label === '全国'){
          this.review.areaVal = {
            value: 6666,
            label: '全国',
            children: []
          }
          return
        }
        let flag = false
        e.forEach(item => {
          if(item.label === '全国'){
            flag = true
          }
        })
        if(flag){
          this.review.areaVal = {
            value: 6666,
            label: '全国',
            children: []
          }
        }
      }
    }
  },
  created(){
    this.getTimeStaus()
    this.advisoryList()
    this.getSectionCascade()
    this.getLabelOptions('')
    this.fetchAreaData()
  },
  mounted(){
    this.headers = { accessToken: getToken() }
  },
  methods:{
    handleClose(){
      this.$confirm('数据未保存，确认关闭？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.labelIds = []
        this.review.labels = []
        this.dialogFormVisible = false
      }).catch(() => {})
    },
    // 投放区域
    fetchAreaData() {
      getAreaList().then(response => {
        this.areaOptions = response.data
        this.areaOptions.unshift({
          value: 6666,
          label: '全国',
          children: []
        })
      })
    },
    //获取资讯状态
    getTimeStaus(){
      auditStatus().then(response => {
        const { code, data } = response
        if (code == 0) {
          this.status = data
        }
      })
    },
    // 资讯条件搜素
    searchAdvisory(){
      this.search.pageNo = 1
      this.search.pageSize = 10

      if(this.timeRange){
        this.search.startTime = new Date(this.timeRange[0])
        this.search.endTime = new Date(this.timeRange[1])
      } else {
        delete this.search.startTime
        delete this.search.endTime
      }
      this.advisoryList()
    },
    // 资讯列表
    advisoryList(){
      this.tableLoading = true
      this.list = []
      advisoryList(this.search).then(response => {
        const { code, data } = response
        if (code == 0) {
          this.list = data.list
          this.total = data.total
          this.tableLoading = false
        }else{
          this.tableLoading = false
        }
      }).catch(err => {
        this.tableLoading = false
      })
    },
    // 多少条一页
    handleSizeChange(val) {
      this.search.pageSize = val
      this.advisoryList()
    },
    // 分页
    handleCurrentChange(val) {
      this.search.pageNo = val
      this.advisoryList()
    },
    // 审核资讯详情
    reviewDetail(index, id, authorId){
      reviewDetail({ id: id }).then(res => {
        if (res.code == 0) {
          this.dialogFormVisible = true
          // if(data.sectionIds){
          //     let sectionIds = data.sectionIds.split(',');
          //     sectionIds = sectionIds.map(e=>e=parseInt(e))
          //     data.sectionIds=sectionIds;
          // }else{
          //     data.sectionIds= [this.sections[0]['value']]
          // }
          if(res.data.cover){
            this.file = [{ name: res.data.cover, url: res.data.cover }]
          }else{
            this.file = []
          }
          this.labelIds.forEach(element => {
            this.review.labels.push(element.id)
            this.review.labelNames.push(element.name)
          })
          this.labelIds = res.data.labels
          this.review.sectionIds = [parseInt(res.data.sectionIds)]
          this.review.content = res.data.content
          this.review.title = res.data.title
          this.review.cover = res.data.cover
          this.review.id = id
          this.review.authorId = authorId
          // this.review.auditId = 3
          this.review.updateTime = new Date().getTime()
          this.review.areaVal = {
            value: 6666,
            label: '全国',
            children: []
          }
        }
      })
    },
    //获取热点推荐
    getSectionCascade() {
      getSectionCascade().then(response => {
        const { code, data } = response
        if (code == 0) {
          this.sections = data
        }
      })
    },
    //获取标签
    getLabelOptions(title){
      getInfoLabels({ labelName:title }).then(response => {
        const { code, data } = response
        if (code == 0) {
          this.labels = data
        }
      })
    },
    // 移除封面
    handleRemove(file, fileList) {
      this.review['cover'] = ''
      this.file = []
    },
    // 上传封面
    handleUploadSuccess(rst, file){
      const { code, data: { picUrlList } } = rst
      const { review } = this
      if (code == 0) {
        review['cover'] = picUrlList[0]
        this.file = [{ name: file.url, url: file.url }]
      }
    },
    // 审核
    checkAdvisory(status){
      let message = ''
      if(status == 0){
        message = '审核不通过'
      }else{
        message = '审核通过'
      }
      // let params=JSON.parse(JSON.stringify(this.review));
      // params.review=[];
      // params.isAuditPass=status;
      // if(params.sectionIds){
      //     if(params.sectionIds.length>1){
      //         params.sectionId=params.sectionIds[length];
      //     }else if(params.sectionIds.length==1){
      //         params.sectionId=params.sectionIds[0]
      //     }
      // }
      // for(let i in this.labelIds){
      //     params.labelIds.push(this.labelIds[i].id)
      // }
      // delete params.sectionIds;
      const params = this.review
      params.isAuditPass = status
      params.sectionId = this.review.sectionIds[0]
      params.labelIds = this.labelIds
      // 修改标签集
      this.labelIds.forEach(element => {
        this.review.labels.push(element.id)
        this.review.labelNames.push(element.name)
      })
      // 投放区域
      if(this.review.areaVal.length === 0){
        params['provinceIds'] = [6666]
      }else{
        if(this.review.areaVal.value == 6666){
          params['provinceIds'] = [6666]
        }else{
          this.review.areaVal.forEach(item => {
            params['provinceIds'].push(item.value)
          })
        }
      }
      // params.labelId = params.labels
      if((params.cover == '' && status == 1) || (params.cover == undefined && status == 1)){
        this.$message({
          message: '封面图片不能为空',
          type: 'error'
        })
      }else{
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            checkAdvisory(params).then(res => {
              // const { code, data } = response;
              // if (code == 0) {
              //     this.$message({
              //         message: `${message}+哎呀错误`,
              //         type: "success"
              //     });
              //     this.dialogFormVisible= false;
              //     status==0 ? this.list[this.review.index].auditStatusDesc='审核不通过' :  this.list[this.review.index].auditStatusDesc='审核通过'
              //     this.list[this.review.index].updateTime= new Date().getTime();
              //     this.list[this.review.index].title= this.review.title;
              // }
              if(res.code == 0){
                this.$message({
                  message: `操作成功，${params.isAuditPass == 1 ? '审核通过' : '审核不通过'}`,
                  type: 'success'
                })
              }else{
                this.$message({
                  message: '操作失败',
                  type: 'error'
                })
              }
              this.labelIds = []
              this.review.labels = []
              this.advisoryList()
              this.dialogFormVisible = false
            })
          }
        })
      }
    }
  }
}
</script>

<style lang="scss">
    .review{
        .inputWidth{
            width: 200px;
        }
        .list, .pagination{
            padding-top: 20px;
        }
        .width{
            width: 180px;
        }
        .sub-navbar{
            height: 50px;
            line-height: 50px;
            position: relative;
            width: 100.1%;
            text-align: right;
            padding-right: 20px;
            -webkit-transition: 600ms ease position;
            transition: 600ms ease position;
            background: -webkit-gradient(linear, left top, right top, from(#20b6f9), color-stop(0%, #20b6f9), color-stop(100%, #2178f1), to(#2178f1));
            background: linear-gradient(90deg, #20b6f9 0%, #20b6f9 0%, #2178f1 100%, #2178f1 100%);
            top:-30px;
        }
        .el-dialog__body{
            padding: 0px;
        }
        .boxCont{
            padding: 30px 20px;
        }
    }
</style>
